/** 屏幕共享流 */
import React from 'react';
import { createRoot } from 'react-dom/client';
import Footer from './Footer';
import StreamContainer from './StreamContainer';
import './styles/screen_stream.less';
import { Provider } from 'react-redux';
import store from '@/store';
import Canvas from './Canvas';

interface ScreenStreamProps {
	visiable?: boolean;
	endScreenMark?: (clientId: string) => void | Promise<any> | undefined;
	clients?: string[];
	screenStream: any;
	screenShareRenderError: (label: string) => void;
}

const createScreenContainer = (props: ScreenStreamProps) => {
	const { endScreenMark, clients = [], screenStream, screenShareRenderError } = props;
	const parentContainer = document.createElement('div');
	const container = document.createElement('div');
	parentContainer.setAttribute('class', 'widget-screen-share-parent-contianer');
	parentContainer.id = 'widget-screen-share-parent-contianer';
	container.setAttribute('class', 'widget-screen-share-contianer');
	container.id = 'widget-screen-share-contianer';
	document.body.appendChild(parentContainer);
	parentContainer.appendChild(container);
	createRoot(container).render(
		<Provider store={store}>
			<StreamContainer screenStream={screenStream} screenShareRenderError={screenShareRenderError} />
			<Footer
				endScreenShare={() => {
					removeScreenContainer();
					if (endScreenMark) {
						clients.map(item => endScreenMark(item));
					}
				}}
			></Footer>
			<Canvas clients={clients}></Canvas>
		</Provider>
	);
};

const removeScreenContainer = () => {
	const container = document.getElementById('widget-screen-share-parent-contianer');
	container && document.body.removeChild(container);
};

const ScreenStream = (props: ScreenStreamProps) => {
	return (
		<div className="screen-share-box">
			<StreamContainer></StreamContainer>
			<Footer></Footer>
		</div>
	);
};

export { createScreenContainer, removeScreenContainer };

export default ScreenStream;
